<?php
class verifyCode
{
	/* 
	 * 返回验证码是否有效
	*/
// 	public static function verify($code) { 
// 		$VerifyCode = M("module_verify_code");
// 		if ($VerifyCode->where("code='$code'")->find()) {
// 			if ($VerifyCode->where("code='$code'")->getField('isClaim') == 0) {
// 				Output::instance()->resultCode(code_success);
// 				return code_success;
// 			} else {
// 				$msg = '奖品已领取';
// 				Output::instance()->resultCode(code_custom_error, $msg);
// 				return code_verifycode_claimed;
// 			}
// 		} else {
// 			$msg = '无效的验证码';
// 			Output::instance()->resultCode(code_custom_error, $msg);
// 			return code_verifycode_notexist;
// 		}
		
// 	}
	
// 	public static function claim($code, $branch) {
// 		$VerifyCode = M("module_verify_code");
		
// 		if ($VerifyCode->where("code='$code'")->find()) {
// 			$ret = $VerifyCode->where("code='$code'")->setField('isClaim', 1);
// 			if ($ret) {
// 				// 使用和claimModule中同样的方式处理字符串，删掉用户名中空格回车等字符
// 				$arr = explode("wx",$branch);
// 				$branch = 'wx' . ((int)$arr[1]);
// 				$VerifyCode->where("code='$code'")->setField('branch', $branch);
// 				$VerifyCode->where("code='$code'")->setField('claimTime', date('Y-m-d H:i:s'));
// 				Output::instance()->resultCode(code_success);
// 				return code_success;
// 			} else {
// 				$msg = '领取失败';
// 				Output::instance()->resultCode(code_custom_error, $msg);
// 				return code_verifycode_claimed;
// 			}
// 		} else {
// 			$msg = '无效的验证码';
// 			Output::instance()->resultCode(code_custom_error, $msg);
// 			return code_verifycode_notexist;
// 		}
// 	}
	
	public static function getList($isClaim, $order='reward', $orderBy="asc", $start=0, $limit=25) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}	
		
		$VerifyCode = M("module_verify_code");
		$condition = "isClaim='$isClaim'";
		$arr = $VerifyCode->where($condition)->order("$order $orderBy")->limit("$start,$limit")->select();
		Output::instance()->module('verifyCode', 'verifycode_list')->objArray($arr, $VerifyCode->where($condition)->count());
	}
	
	public static function getRewardTotal($mid){
		
		$cid = 	Session::$user['customerId'];
		Session::switchCustomer($cid);
		Log::write('enter getRewardTotal cid is:'.$cid);
		if($cid == 0){
			$prefix = C('ORIGINAL_DB_PREFIX');
		}else{
			$prefix = C('ORIGINAL_DB_PREFIX').$cid.'_';
		}
		
		$ModuleVerifyCode = new Model();
		$totalCountSql = 'SELECT materialId as mid,reward,count(*) as tnum FROM '
		.$prefix.'module_verify_code  where materialId = '.$mid.' group by `reward` order by reward DESC';
		$totalResult = $ModuleVerifyCode->query($totalCountSql);
		
// 		Log::write('get reward total sql is:'.$ModuleVerifyCode->getLastSql());
		return $totalResult;
		Output::instance()->objArray($totalResult, count($totalResult));
		
	}
	public static function getRewardTotalNum($mid){
		
		$cid = 	Session::$user['customerId'];
		Session::switchCustomer($cid);
// 		Log::write('enter getRewardTotal cid is:'.$cid);
		if($cid == 0){
			$prefix = C('ORIGINAL_DB_PREFIX');
		}else{
			$prefix = C('ORIGINAL_DB_PREFIX').$cid.'_';
		}
		
		$ModuleVerifyCode = new Model();

		$totalCountSql = 'SELECT count(distinct reward) as totalNum FROM '
		.$prefix.'module_verify_code  where materialId = '.$mid;
		
		$totalResult = $ModuleVerifyCode->query($totalCountSql);
		
		return $totalResult;
		
	}
	
	/**
	 * 获取各种奖励总数,领取数,使用数
	 * @param unknown_type $mid
	 */
	
	public static function rewardStatistics($mid){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$cid = 	Session::$user['customerId'];
		Session::switchCustomer($cid);
		
		if($cid == 0){
			$prefix = C('ORIGINAL_DB_PREFIX');
		}else{
			$prefix = C('ORIGINAL_DB_PREFIX').$cid.'_';
		}
		//SELECT reward,count(*) as tnum FROM wx_2_module_verify_code  where materialId = 4 group by `reward` order by reward DESC;
		
		$ModuleVerifyCode = new Model();
// 		$ModuleVerifyCode = D('module_verify_code');
		$totalCountSql = 'SELECT materialId as mid,reward,count(*) as tnum FROM '
					.$prefix.'module_verify_code  where materialId = '.$mid.' group by `reward` order by reward DESC';
		$totalResult = $ModuleVerifyCode->query($totalCountSql);
		
		$isCreateCountSql = 'SELECT reward,count(*) as isCreatenum FROM '
					.$prefix.'module_verify_code  where materialId = '.$mid.' and fromUserName !="" group by `reward` order by reward DESC';
		
		$isClaimCountSql = 'SELECT reward,count(*) as isClaimnum FROM '
					.$prefix.'module_verify_code  where materialId =  '.$mid.' and fromUserName !="" and isClaim = 1 group by `reward` order by reward DESC';
		
		$isCreateResult = $ModuleVerifyCode->query($isCreateCountSql);
		$isClaimResult = $ModuleVerifyCode->query($isClaimCountSql);
		$primaryArray = array() ;
		
		if($totalResult){
			for($i=0;$i<count($totalResult);$i++){
				$temArray = array(
						"mid"=>$totalResult[$i]["mid"],
						"reward"=>$totalResult[$i]["reward"],
						"totalNum"=>(int)$totalResult[$i]["tnum"],
						"createNum"=>0,
						"claimNum"=>0,
				);
				
				if($isCreateResult){
					for($j=0;$j<count($isCreateResult);$j++){
						if($isCreateResult[$j]["reward"] == $totalResult[$i]["reward"]){
							$temArray["createNum"] = (int)$isCreateResult[$j]["isCreatenum"];
						}
					}
				}
				
				if($isClaimResult){
					for($k=0;$k<count($isClaimResult);$k++){
						if($isClaimResult[$k]["reward"] == $totalResult[$i]["reward"]){
							$temArray["claimNum"] = (int)$isClaimResult[$k]["isClaimnum"];
						}
					}
				}
				array_push($primaryArray,$temArray);
			}
		}
		
		Output::instance()->objArray($primaryArray, count($primaryArray));
	}
	
	
	public static function getCreateAndClaimStatistics($mid,$reward,$startDate='',$endDate=''){
		
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$cid = 	Session::$user['customerId'];
		Log::write('user customerId is:'.Session::$user['customerId']);
		Session::switchCustomer($cid);
		
		if($cid == 0){
			$prefix = C('ORIGINAL_DB_PREFIX');
		}else{
			$prefix = C('ORIGINAL_DB_PREFIX').$cid.'_';
		}
		
		$ModuleVerifyCode = new Model();
		
		$isCreateCountSql = 
		'SELECT DATE_FORMAT( createTime, "%Y-%m-%d" ) as createDateTime,'
		.'createTime,reward,COUNT(*) as number FROM '
		.$prefix.'module_verify_code  where reward = "'.$reward
		.'" and materialId = '.$mid.' and fromUserName !="" GROUP BY DATE_FORMAT( createTime, "%Y-%m-%d" )';
		
		
		
		$isClaimCountSql = 
		'SELECT DATE_FORMAT( claimTime, "%Y-%m-%d" ) as claimDateTime,'
		.'claimTime,reward,COUNT(*) as number FROM '
		.$prefix.'module_verify_code  where reward = "'.$reward
		.'" and materialId = '.$mid.' and fromUserName !="" and isClaim = 1  GROUP BY DATE_FORMAT( claimTime, "%Y-%m-%d" )';
		
		
		$createResult = $ModuleVerifyCode->query($isCreateCountSql);
		
		Log::write('createCount sql is:'.$ModuleVerifyCode->getLastSql());
		$claimResult =  $ModuleVerifyCode->query($isClaimCountSql);
		
		Log::write('claimCount sql is:'.$ModuleVerifyCode->getLastSql());
		
		$result = array();
		//统计的天数差值
		$dateCount = round(strtotime($endDate) - strtotime($startDate))/3600/24;
		Log::write('dateCount is:'.$dateCount);
		
		for($i = 0 ; $i <= $dateCount ; $i++){
			$temDate = $i*24*60*60 + strtotime(date('Y-m-d',strtotime($startDate)));
			
			$temArray = array(
					"dateTime"=>date('Y-m-d',$temDate),
					"time"=>date('m-d',$temDate),
					"reward"=>$reward,
					"createNumber"=>0,
					"claimNumber"=>0
			);
			
			if($createResult){
				for($j = 0;$j<count($createResult);$j++){
					if($temDate == strtotime($createResult[$j]['createDateTime'])){
						$temArray["createNumber"] = (int)$createResult[$j]['number'];
					}
				}
			}
			
			if($claimResult){
				for($k = 0;$k<count($claimResult);$k++){
					if($temDate == strtotime($claimResult[$k]['claimDateTime'])){
						$temArray["claimNumber"] = (int)$claimResult[$k]['number'];
					}
				}
			}
			array_push($result,$temArray);
		}
		
		Output::instance()->objArray($result, count($result));
	}
	
	
	public static function getQuerySystemStatistics($mid,$startDate='',$endDate='',$branch=null){

		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$cid = 	Session::$user['customerId'];
		Session::switchCustomer($cid);
		
		if($cid == 0){
			$prefix = C('ORIGINAL_DB_PREFIX');
		}else{
			$prefix = C('ORIGINAL_DB_PREFIX').$cid.'_';
		}
		$ModuleVerifyCode = new Model();
		if ($branch == null) {
			$sql = 'SELECT reward,branch,count(*) as number FROM '.
			$prefix.'module_verify_code where fromUserName !="" and isClaim = 1 and materialId='.$mid.' and claimTime >= "'.$startDate.'" AND claimTime <= "'.$endDate.'" group by reward order by reward DESC';
		}else{
			$sql = 'SELECT reward,branch,count(*) as number FROM '.
			$prefix.'module_verify_code where fromUserName !="" and isClaim = 1 and materialId='.$mid.' and branch="'.$branch.'" and claimTime >= "'.$startDate.'" AND claimTime <= "'.$endDate.'" group by reward order by reward DESC';
		}
		$result = $ModuleVerifyCode->query($sql);
		
		Log::write($ModuleVerifyCode->getLastSql());
		/*
		if($result){
			$temArray = array(
					"reward"=>'总计',
					"branch"=>$branch,
					"number"=>0
			);
			$totalNum = 0;
			for($i=0;$i<count($result);$i++){
				$totalNum += (int)$result[$i]["number"];
			}
			$temArray["number"] = $totalNum;
			
			array_push($result,$temArray);
		}
		*/
		Output::instance()->objArray($result, count($result));
	}
	
	public static function getQuerySystemByReward($mid,$reward,$startDate='',$endDate=''){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$cid = 	Session::$user['customerId'];
		Session::switchCustomer($cid);
		
		if($cid == 0){
			$prefix = C('ORIGINAL_DB_PREFIX');
		}else{
			$prefix = C('ORIGINAL_DB_PREFIX').$cid.'_';
		}
		$ModuleVerifyCode = new Model();
		
		
		$sql = 'SELECT v.reward,v.branch,u.fullName,count(*) as number FROM '.
			$prefix.'module_verify_code v left join wx_customer_user u on v.branch=u.email  where fromUserName !="" and isClaim = 1 and materialId='.$mid
			.' and reward="'.$reward
			.'" and claimTime >= "'.$startDate.'" and claimTime <= "'.$endDate.'" and u.customerId='.$cid.' group by branch order by branch DESC';
		
		$result = $ModuleVerifyCode->query($sql);
		
		Log::write('reward statistics sql is:'.$ModuleVerifyCode->getLastSql());
		Output::instance()->objArray($result, count($result));
	}
	
}